<template>
  <div class="content">
    <div class="cloud-header">
      <h2>数据管理</h2>
    </div>
    <div class="cloud-layout">
      <Layout style="min-height: 500px;">
        <Sider>
          <div class="cloud-menus">
            <Menu :datas="menu" ref="menu" className="h-menu-white" @click="chooseTable"></Menu>
          </div>
        </Sider>
        <Layout v-if="JSON.stringify(item_list) !== '{}'">
          <HHeader>
            <div class="cloud-tools">
              <ButtonGroup>
                <Button icon="h-icon-inbox" @click="dataDump">导出</Button>
                <Button icon="h-icon-plus" @click="showModal('添加数据')">添加</Button>
                <Button icon="h-icon-trash" @click="dataDel">删除</Button>
                <Button icon="h-icon-refresh" @click="dataRefresh">刷新</Button>
              </ButtonGroup>
            </div>
          </HHeader>
          <Content>
            <Table class="cloud-table" :datas="datas" :checkbox="true" :selectRow="true" @select="onSelect" selectWhenClickTr>
              <TableItem :width="135" v-for="item,key in item_list" :title="item.title" :prop="key" :format="itemFormat" :key="key" v-if="key !== '_userid' && key !== '_uniqueid'"></TableItem>
              <TableItem title="操作" align="center" :width="100" fixed="right"><template slot-scope="{data}"><button class="h-btn h-btn-s h-btn-blue" @click.stop="showModal('编辑数据',data)"><i class="h-icon-edit"></i> 编辑</button></template></TableItem>
              <div slot="empty">暂无数据</div>
            </Table>
            <Pagination class="cloud-page" v-model="pagination" align="center" @change="currentChange" small></Pagination>
          </Content>
        </Layout>
      </Layout>
    </div>
    <Modal v-model="openModal" className="m-body">
      <div slot="header">{{edit_data.title}}</div>
      <!-- <div :style="{'height': height ? '800px' : 'auto'}">
        <div>这是Vue自定义的弹出框</div>
        <div><Select dict="simple" v-width="160"></Select></div>
      </div> -->
      <code-editor v-model="edit_data.data" mode="javascript"></code-editor>
      <div slot="footer">
        <button class="h-btn" @click="closeModal">取消</button>
        <button class="h-btn h-btn-primary" @click="saveData">确定</button>
      </div>
    </Modal>
  </div>
</template>
<script type="text/javascript">
import CodeEditor from '@/components/code-editor'
export default {
  data() {
    return {
      menu: [{
        title: '数据库表',
        icon: 'h-icon-calendar',
        key: 'database',
        children: []
      }],
      //表格
      tables: {},
      //选中表
      choose_table: '',
      //表头列表
      item_list: {},
      //展示数据
      datas: [],
      openModal: false,
      //修改数据
      edit_data: {
        title: '编辑',
        id: '',
        data: ''
      },
      selectId: [],
      //分页数据
      pagination: {
        page: 1,
        size: 10,
        total: 100
      }
    };
  },
  components: {
    CodeEditor
  },
  /**
   * 页面加载执行
   * @return {[type]} [description]
   */
  mounted() {
    this.getTables()
  },
  methods: {
    //获取我的表格
    getTables() {
      this.$cloud.tables().all({ AppID: this.$cloud.AppID }).then(res => {
        this.menu[0].children = []
        for (var i in res) {
          let obj = {
            title: res[i].explain,
            key: res[i].name
          }
          this.tables[res[i].name] = res[i]
          this.menu[0].children.push(obj)
        }
      })
    },
    //选中表
    chooseTable(e) {
      if (e.key !== 'database') {
        this.item_list = this.tables[e.key].fields
        this.choose_table = e.key
        this.datasList()
        this.datasCount()
      }
    },
    //选中处理
    onSelect(data) {
      this.selectId = []
      for (var i in data) {

        this.selectId.push(data[i]._id)
      }
    },
    //删除选中数据
    dataDel() {
      let that = this
      this.$Modal({
        title: '提示',
        content: '确定要删除选中内容吗?',
        width: 300,
        buttons: [{
          type: 'cancel',
          name: '关闭'
        }, {
          type: 'ok',
          name: '确认',
          color: 'primary'
        }],
        events: {
          $init: (modal) => {
            // trigger when modal inited
          },
          $close: (modal) => {
            // trigger when modal closed
          },
          ok: (modal) => {
            that.$cloud.name(that.choose_table).where({ _id: ['in', that.selectId] }).delete()
              .then(res => {
                console.log(res)
                if (res) {
                  that.$Message({ type: 'success', text: "删除成功" });
                  that.datasList()
                  modal.close();
                } else {
                  that.$Message({ type: 'warn', text: "删除失败" });
                }
              })
              .catch(err => {
                console.log(err)
              })
          },
          cancel: (modal) => {
            modal.close();
          }
        }
      });
    },
    //分页
    currentChange(value) {
      this.pagination = value
      this.datasList()
    },
    //数据
    datasList() {
      this.$cloud.name(this.choose_table).order('_id DESC').page(this.pagination.page, this.pagination.size).select()
        .then(res => {
          this.datas = res
        })
        .catch(err => {
          console.log(err)
        })
    },
    //数据总数
    datasCount() {
      this.$cloud.name(this.choose_table).count()
        .then(res => {
          this.pagination.total = res
        })
        .catch(err => {
          console.log(err)
        })

    },
    //数据导出
    async dataDump() {
      let data = await this.$cloud.name(this.choose_table).limit(-1).select()
      if (data.length === 0) {
        this.$Message({ type: 'warn', text: "暂无数据" });
        return
      }
      let filename = this.choose_table + '.json'
      let text = JSON.stringify(data)
      var element = document.createElement('a');
      element.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(text));
      element.setAttribute('download', filename);
      element.style.display = 'none';
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
    },
    //打开编辑弹窗
    showModal(title, data = '') {
      this.edit_data.title = title
      if (data && data._id) {
        this.edit_data.id = data._id
        delete data._heyui_uuid
        delete data._id
        data = JSON.stringify(data)
        data = data.replace(/\\n/g, '[换行]')
        data = JSON.parse(data)
        data = this.pretty_format(data)
        this.edit_data.data = data
      } else {
        this.edit_data.id = ''
      }
      this.openModal = true
    },
    //关闭编辑弹窗
    closeModal(title) {
      this.openModal = false
    },
    //数据刷新
    dataRefresh() {
      this.$Message({ type: 'success', text: "添加成功" });
      this.datas = []
      this.datasList()
    },
    async saveData() {
      let data = JSON.parse(this.edit_data.data)
      data = JSON.stringify(data)
      data = data.replace(/\\n/g, '[换行]')
      data = JSON.parse(data)
      let result = ''
      if (this.edit_data.id) {
        this.$cloud.name(this.choose_table).where({ _id: this.edit_data.id }).update(data)
          .then(res => {
            if (res) {
              this.$Message({ type: 'success', text: "保存成功" });
              this.datasList()
              this.openModal = false
            } else {
              this.$Message({ type: 'warn', text: "保存失败" });
            }
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.$cloud.name(this.choose_table).insert(data)
          .then(res => {
            if (res) {
              this.$Message({ type: 'success', text: "添加成功" });
              this.datasList()
              this.openModal = false
            } else {
              this.$Message({ type: 'warn', text: "添加失败" });
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    //字段处理
    itemFormat(value) {
      if (Object.prototype.toString.call(value) === "[object Array]") {
        return '(Array)' + value.length + ' Elements'
      } else if (Object.prototype.toString.call(value) === "[object Object]") {
        let num = 0
        for (var i in value) {
          num++
        }
        return '(Document) ' + num + ' Fields'
      } else {
        if (typeof value === 'string' && value.length > 16) {
          return value.substring(0, 16) + '...'
        } else {
          return value

        }
      }
    },
    /*
     * 格式化
     * */
    pretty_format(obj, indent_num = 2) {
      if (obj === null) return 'null';
      if (obj === undefined) return 'undefined';
      if (typeof obj === 'string') return '"' + obj + '"';
      if (typeof obj !== 'object') return String(obj);

      let indent = ''
      for (var i = 0; i < indent_num; i++) {
        indent += ' '
      }

      if (Object.prototype.toString.call(obj) === "[object Array]") {
        let result = '[';
        let num = 0;
        for (var key in obj) {

          //第一个对象前不跟逗号
          let comma = ','
          if (num === 0) {
            comma = ''
          }
          result += comma + '\n' + indent + this.pretty_format(obj[key], indent_num + 2);
          num++;
        }
        return result += '\n' + indent + ']';
      } else {
        let result = '{';
        let num = 0;
        for (var key in obj) {

          //第一个对象前不跟逗号
          let comma = ','
          if (num === 0) {
            comma = ''
          }
          result += comma + '\n' + indent + '"' + key + '" : ' + this.pretty_format(obj[key], indent_num + 2);
          num++;
        }
        return result += '\n' + indent + '}';
      }


    }
  }
};

</script>
<style type="text/css">
.cloud-table {
  margin: 20px;
}

.cloud-page {
  margin-bottom: 20px;
}

.m-body .h-notify-container {
  width: 800px;
}

</style>
